package com.zjp.mall.controller;

import com.zjp.mall.pojo.User;
import com.zjp.mall.service.UserService;
import com.zjp.mall.vo.WechatEncryptVO;
import com.zjp.mall.util.HttpHelper;
import com.zjp.mall.util.JsonUtil;
import com.zjp.mall.util.WechatDecrypt;
import com.zjp.mall.vo.WeChatUserInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.beans.Transient;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wechat")
public class WechatModule {


    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.secret}")
    private String secret;

    Logger logger = LoggerFactory.getLogger(WechatModule.class);


    @Autowired
    private UserService userService;

    @Resource(name = "redisTemplate")
    private ValueOperations<String, Object> vOps;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(){
        logger.info("111");
        return  "hello" + appId + secret;
    }


    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public  Map<String,String> doLogin(@RequestParam(name = "code") String code, HttpSession session){
        String url = "";
        Map<String,String> rtn = new HashMap<String,String>();
        try {
            url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
            url = url.replaceAll("APPID",appId);
            url = url.replaceAll("SECRET",secret);
            url = url.replaceAll("JSCODE",code);
            logger.info("请求微信openId地址"+url);
            String response = HttpHelper.get(url);
            logger.info("请求微信openId返回"+response);
            Map<String ,String > responseJson = JsonUtil.strToObj(response, HashMap.class);
            if(responseJson == null || responseJson.get("errcode") != null){
                rtn.put("data","error");
                return rtn;
            }
            String openId = responseJson.get("openid");
            String session_key = responseJson.get("session_key");
            logger.info("openId=" + openId);
            logger.info("session_key=" + session_key);
            session.setAttribute("openId",openId);
            session.setAttribute("sessionKey",session_key);
            rtn.put("data","success");
            rtn.put("sessionId",session.getId());

            return rtn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtn;
    }

    @RequestMapping(value = "/getUserInfo",method = RequestMethod.POST)
    public String getUserInfo(@RequestBody WechatEncryptVO wechatUserInfo, HttpSession session ){

        String openId = (String) session.getAttribute("openId");
        String sessionKey = (String) session.getAttribute("sessionKey");
        logger.info("openId="+openId);
        logger.info("sessionKey="+sessionKey);
        logger.info("rawData="+wechatUserInfo.getRawData());
        logger.info("signature="+wechatUserInfo.getSignature());
        logger.info("encryptedData="+wechatUserInfo.getEncryptedData());
        logger.info("iv="+wechatUserInfo.getIv());

        try {
            String decryptedData = WechatDecrypt.decode(wechatUserInfo.getEncryptedData(),sessionKey,wechatUserInfo.getIv());
            WeChatUserInfoVO weChatUserInfoVO = JsonUtil.strToObj(decryptedData,WeChatUserInfoVO.class);
            String nickname = weChatUserInfoVO.getNickName();
            String avatarUrl = weChatUserInfoVO.getAvatarUrl();
            logger.info("nickname=" + nickname);
            logger.info("avatarUrl=" + avatarUrl);
            User user = userService.selectByOpenId(openId);
            if(user == null){
                user = new User();
                user.setStrOpenId(openId);
                user.setlSex(Boolean.parseBoolean(weChatUserInfoVO.getGender()));
                user.setStrUserName(nickname);
                int lid = userService.insert(user);
                logger.info("lid="+lid);
                logger.info("userId="+user.getLid());
            }
            return "success";
        } catch (Exception e) {
            logger.error("",e);
        }
        return "error";
    }


    @RequestMapping(value = "getUser",method = RequestMethod.GET)
    public String getUser(@RequestParam(value = "openId") String openId){
        User user = userService.selectByOpenId(openId);
        System.out.println(user.getStrUserName());
        return "success";
    }

    @RequestMapping(value = "insertAndDelete")
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public String insertAndDelete(){
        User user = new User();
        user.setStrOpenId("111");
        userService.insert(user);
        System.out.println("11111111111111111111111111111");
        userService.deleteThrowException();
        return  "success";
    }

    @RequestMapping(value = "setRedis")
    public String setRedis(@RequestParam(value = "key") String key,@RequestParam(value = "value") String value){
        vOps.set(key,value);
        return "success";
    }
    @RequestMapping(value = "getRedis")
    public String getRedis(@RequestParam(value = "key") String key){
        return (String)vOps.get(key);
    }
}


